package remote;

import infrastructure.exceptions.SessionException;

import java.io.IOException;
import java.io.Serializable;

import dal.User;


/**
 * This class represents a session user has with the server 
 * @author sashas
 *
 */
public class Session implements Serializable{

	
	public static class SessionId{
		
		private long id;
		
		public SessionId(long id){
			this.id = id;
		}
		
		
		public long toLong(){
			return id;
		}
		
		@Override
		public boolean equals(Object other) {
			
			if (this == other){
				return true;		
			}else if ((null != other) && (other instanceof SessionId)){				
				SessionId otherSession = (SessionId)other;			
				return this.id == otherSession.id;		
			}else{
				return false;
			}	
		}
		
		@Override
		public int hashCode() {
			return (int)(id ^ (id >>> 32));
		}
		
		@Override
		public String toString() {
			return Long.toString(id);
		}
		
	}	
	
	/** Keeps session id*/
	private SessionId sessionID;
	
	/** Keeps user of the session*/
	private transient User user;
	
	
	

	public Session(SessionId id,User user){
		sessionID = id;
		this.user = user;
	}
	
	public SessionId getSessionID() {
		return sessionID;
	}

	@Override
	public boolean equals(Object other) {
		if (this == other){
			return true;		
		}else if ((null != other) && (other instanceof Session)){				
			Session otherSession = (Session)other;			
			return this.getSessionID().equals(otherSession.getSessionID());		
		}else{
			return false;
		}		
	}
	
	@Override
	public int hashCode() {
		return getSessionID().hashCode();
	}
	
	public boolean isGuest(){
		return this == SessionManager.getGuestSession();
	}
	
	public User getUser() {
		return user;
	}
	
	private void writeObject(java.io.ObjectOutputStream out) throws IOException{
		out.writeLong(getSessionID().toLong());
	}
	
	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
		
		Session.SessionId readId = new Session.SessionId(in.readLong());
		
		try{
			SessionManager.getInstance().getSession(readId);
		}catch(SessionException ex){
			throw new IOException("Non existing session",ex);
		}
		
	}
	
	@Override
	public String toString() {
		return "Session id '" + sessionID + "' user '" + user.getUsername() + "'";
	}

	
	
}
